package com.dituhui.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dituhui.gps.service.GetTrack;
import com.dituhui.gps.vo.GPSLine;
import com.dituhui.gps.vo.GPSPoint;
import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.ESTool;
import com.dituhui.tool.io.RedisTool;
import com.dituhui.tool.util.StringUtil;

public class Monitor extends HttpServlet {
	private static Logger LOGGER = Logger.getLogger(GetTrack.class);
	private String redisUrl;
	private int redisPort;
	private String redisPwd;
	private String uploadPicIndex;
	private String historyESUrl;

	public void init() throws ServletException {
		LOGGER.info("Monitor.init()");
		redisUrl = Constants.getValue("REDIS.HOST", "gps_config.properties");
		redisPort = Integer.parseInt(Constants.getValue("REDIS.PORT", "gps_config.properties"));
		redisPwd = Constants.getValue("REDIS.PWD", "gps_config.properties");
		// LOGGER.info("redisUrl=" + redisUrl);
		this.uploadPicIndex = Constants.getValue("uploadPicIndex", "web_config.properties");
		this.historyESUrl = Constants.getValue("HistoryESUrl", "gps_config.properties");
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String command = request.getParameter("cmd");
		String userKey = request.getParameter("userKey");
		if (userKey == null || userKey.length() == 0 || userKey.equals(StringUtil.NULL)) {
			// 空值置为null
			userKey = null;
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		if (command == null) {
			out.print("参数非法");
		} else {
			StringBuilder output = new StringBuilder();
			if ("list".equals(command)) {
				try {
					RedisTool redisTool = new RedisTool();
					String keysQueryClause;
					if (userKey == null) {
						keysQueryClause = "pos_*";
					} else {
						keysQueryClause = "pos_" + userKey + StringUtil.Underline + "*";
					}
					Set<String> redisKeys = redisTool.getKeys(keysQueryClause, redisUrl, redisPort, redisPwd);
					List<GPSPoint> gpsPoints = new ArrayList<GPSPoint>();
					for (String redisKey : redisKeys) {
						String value = redisTool.getString(redisKey, redisUrl, redisPort, redisPwd);
						GPSPoint gpsPoint = GPSPoint.parseCSVString(value);
						gpsPoints.add(gpsPoint);
					}
					GPSLine.sortByTime(gpsPoints);
					output.append("gpsPoints.size() = " + gpsPoints.size());
					output.append("<br>");
					// 最多输出15条
					int n = 15;
					String count = request.getParameter("count");
					if (count != null && count.length() > 0) {
						try {
							n = Integer.parseInt(count);
						} catch (Exception e) {
							LOGGER.info("解析count失败，count=" + count);
						}
					}
					// 倒序
					for (int i = gpsPoints.size() - 1; i >= 0 && i >= gpsPoints.size() - n; i--) {
						GPSPoint gpsPoint = gpsPoints.get(i);
						output.append(gpsPoint.toString());
						output.append("<br>");
					}
				} catch (Exception e) {
					String message = "查询发生异常。";
					LOGGER.warn(message, e);
				}
			} else if ("pics".equals(command)) {
				// 查看全部图片
				String[] queryColumnNames = null;
				String[] queryColumnValues = null;
				List<String> result = ESTool.query(this.uploadPicIndex, queryColumnNames, queryColumnValues, this.historyESUrl);
				output.append("count=");
				output.append(result.size());
				for (String s : result) {
					output.append("<br>");
					output.append(s);
				}
				// } else if ("log".equals(command)) {
				// // 记录日志
				// String log = request.getParameter("log");
				// LOGGER.info("APP_LOG:" + log);
				// output.append(log);
			}
			out.print(output.toString());
			out.flush();
			out.close();
		}
	}
}
